#encoding=utf8

import os
import time
import win32process
import win32pdh
import win32event
from datetime import datetime

import socket
import thread
import threading


flag = False

def get_processes():
    win32pdh.EnumObjects(None, None, win32pdh.PERF_DETAIL_WIZARD)
    junk, instances = win32pdh.EnumObjectItems(None,None,'Process', win32pdh.PERF_DETAIL_WIZARD)

    proc_dict = {}
    for instance in instances:
        if proc_dict.has_key(instance):
            proc_dict[instance] = proc_dict[instance] + 1
        else:
            proc_dict[instance]=0

    proc_ids = []
    for instance, max_instances in proc_dict.items():
        for inum in xrange(max_instances+1):
            hq = win32pdh.OpenQuery() # initializes the query handle 
            try:
                path = win32pdh.MakeCounterPath( (None, 'Process', instance, None, inum, 'ID Process') )
                counter_handle=win32pdh.AddCounter(hq, path) #convert counter path to counter handle
                try:
                    win32pdh.CollectQueryData(hq) #collects data for the counter 
                    type, val = win32pdh.GetFormattedCounterValue(counter_handle, win32pdh.PDH_FMT_LONG)
                    #proc_ids.append((instance, val))
                    proc_ids.append(instance)
                except win32pdh.error, e:
                    #print e
                    pass

                win32pdh.RemoveCounter(counter_handle)

            except win32pdh.error, e:
                #print e
                pass
            win32pdh.CloseQuery(hq) 

    return proc_ids

   
class Operation(threading._Timer):
    def __init__(self, *args, **kwargs):
        threading._Timer.__init__(self, *args, **kwargs)
        self.setDaemon(True)

    def run(self):
        while True:
            self.finished.clear()
            self.finished.wait(self.interval)
            if not self.finished.isSet():
                self.function(*self.args, **self.kwargs)
            else:
                return self.finished.set()

class Manager(object):
    ops = []
    def add_operation(self, operation, interval, args=[], kwargs={}):
        op = Operation(interval, operation, args, kwargs)
        self.ops.append(op)
        thread.start_new_thread(op.run, ())

    

def monitor_server(tlist):
    global flag
    print len(tlist)
    if 'qinyi_server.exe' not  in tlist:
            print 'new'
        #if not flag:
            si = win32process.STARTUPINFO()
            handle   = win32process.CreateProcess('qinyi_server/qinyi_server.exe', '',None , None , 1
                               ,win32process.CREATE_NEW_CONSOLE , None , None ,si) #CREATE_NEW_CONSOLE
            win32event.WaitForSingleObject(handle[0],-1)
            
            flag = True

            
            try:
                s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
                login_content ='00000080`1000`0100`006`20100401112314`006	123456`xx101010`ZTO-SH.001.002` \n'.encode('utf-16-le')
                s.connect(('127.0.0.1',2345))
                s.send(login_content)
                data = s.recv(100)
                #s.close()
                r_str =  str(data)
                print r_str.decode('utf-16-le')
                if '00`' in r_str:
                    print 'login ok'
                    pass
                if '00`' not in r_str:
                    print 'error'
                    #print 'restart server1'
                    #try:
                    #    os.system('taskkill  /f /IM "qinyi_server2#####.exe"')
                    #except Exception ,e:
                    #    print str(e)
                    #os.system('taskkill  /f /IM "qinyi_server2.exe"')
                    #win32process.CreateProcess('qinyi_server2.exe', '',None , None , 0
                    #                       ,win32process. CREATE_NO_WINDOW , None , None ,win32process.STARTUPINFO())
            except Exception ,e:
                print str(e)
                #print 'restart server2'
                #os.system('taskkill  /f /IM "qinyi_server2#####.exe"')
                #win32process.CreateProcess('dist/qinyi_server2.exe', '',None , None , 0
                #                       ,win32process. CREATE_NO_WINDOW , None , None ,win32process.STARTUPINFO())
    else:
        pass
  

def xx():
    try:
        s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
        login_content ='00000080`1000`0100`006`20100401112314`006	123456`xx101010`ZTO-SH.001.002` \n'.encode('utf-16-le')
        s.connect(('127.0.0.1',2345))
        s.send(login_content)
        data = s.recv(100)
        print r_str.decode('utf-16-le')
    except Exception,e:
        print str(e)
        try:
            os.system('taskkill  /f /IM "qinyi_server.exe"')
        except:
            pass
        si = win32process.STARTUPINFO()
        handle   = win32process.CreateProcess('qinyi_server/qinyi_server.exe', '',None , None , 1
                               ,win32process.CREATE_BREAKAWAY_FROM_JOB , None , None ,si) #CREATE_NEW_CONSOLE
        win32event.WaitForSingleObject(handle[0],-1)


if __name__ == '__main__':
    
    while 1:
        os.system('cls')
        print '\n' *5
        print datetime.now()
    #timer = Manager()
    #timer.add_operation(monitor_server,.3)
        tlist =  get_processes()
        #tlist = os.popen('tasklist').read()
        monitor_server(tlist)
        #xx()
        time.sleep(.3)
        
